import {defineStore} from "pinia";
import {computed, ref, watch} from "vue";
import {
    ProductCategoryCreate, ProductCategoryDelete,
    ProductCategoryList, ProductCategoryUpdate,
} from "@/services/api/product/category.ts";
import useMessage from "@/utils/useMessage.ts";
import {useOrgStore} from "@/store/modules/organization";

export const useProductCategoryStore = defineStore('productCategory', ()=>{
    const dataSource = ref<Category[]>([])
    const loading = ref<boolean>(false)
    const orgStore = useOrgStore()
    const searchTerm = ref<string>('')
    /**
     * 返回筛选过滤收数据
     */
    const data = computed(()=>{
        const term = searchTerm.value.trim().toLowerCase()
        if (!term) return dataSource.value
        // 递归过滤函数
        const filterTree = (nodes: Category[]): Category[] => {
            return nodes.map(item => {
                    const matches = item.name.toLowerCase().includes(term)
                    const filteredChildren = item.children ? filterTree(item.children) :null
                    // 如果自己匹配 或 子节点有匹配，则保留
                    if (matches || filteredChildren) {
                        return {...item, children: filteredChildren}
                    }
                    return null
                })
                .filter(Boolean) as Category[]
        }
        return filterTree(dataSource.value)
    })
    const getList = async (force?:boolean)=>{
        if(!force && dataSource.value.length > 0){
             return
        }
        try {
            loading.value = true
            const res = await ProductCategoryList(orgStore.id)
            if (res.code === 200){
                dataSource.value = res.data
            }
        }catch ( e){
            useMessage(500,'请求失败，请重试或是联系我们');
        }finally {
            setTimeout(()=>loading.value = false,100)
        }
    }
    // 监听组织机构id变化，如果改变重新请求
    watch(()=>orgStore.id,async ()=>{
        await getList(true)
    })
    const create = async (data:CategoryForm)=>{
        const res = await ProductCategoryCreate(data)
        if (res.code === 200){
            await getList(true)
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const update = async (data:CategoryForm)=>{
        if (!data.id){
            useMessage(500,'请选择要修改的分类')
            return false
        }
        const res = await ProductCategoryUpdate(data.id,data)

        if (res.code === 200){
            const item = dataSource.value.find(item=>item.id === data.id)
            if (item){
                Object.assign(item,data)
            }
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const remove = async (id:number)=>{
        const res = await ProductCategoryDelete(id)
        if (res.code === 200){
            dataSource.value = dataSource.value.filter(item=>item.id !== id)
        }
        useMessage(res.code,res.message)
    }
    return {
        dataSource,
        getList,
         create,
         update,
         remove,
        data,
        searchTerm,
        loading
    }
},{
    persist: {
        pick: ['dataSource']
    }
})